﻿using Digitalmes.Core.Domain.Eitites;
using Digitalmes.Core.Domain.Repositories;
using Microsoft.Extensions.Caching.Memory;

namespace Digitalmes.Core.Services.Impl;

internal sealed class ParamStandardService(IRepository<ParamStandard> repo, IMemoryCache memoryCache) : IParamStandardService
{
    const string CacheName = "___Cache_Param_Standard";

    public async Task<List<ParamStandard>> GetStandardListAsync()
    {
        return await memoryCache.GetOrCreateAsync(CacheName, async (_) =>
        {
            var item = await repo.GetListAsync();
            return item;
        }) ?? [];
    }

    /// <summary>
    /// 获取参数标准
    /// </summary>
    /// <param name="paramCode">参数名称</param>
    /// <returns></returns>
    public async Task<(bool ok, double? min, double? max)> GetStandardAsync(string paramCode)
    {
        var items = await GetStandardListAsync();
        if (items?.Count == 0)
        {
            return (false, default, default);
        }

        var item = items!.FirstOrDefault(s => s.ParamCode == paramCode && s.IsEnabled);
        if (item == null)
        {
            return (false, default, default);
        }

        return (true, item.MinLimit, item.MaxLimit);
    }

    public async Task ChangeStandardAsync(string paramCode, double min, double max, bool isEnabled)
    {
        var item = await repo.FirstOrDefaultAsync(m => m.ParamCode == paramCode);
        if (item == null)
        {
            return;
        }

        item.MinLimit = min;
        item.MaxLimit = max;
        item.IsEnabled = isEnabled;
        var ok = await repo.UpdateAsync(item);
        if (ok)
        {
            memoryCache.Remove(CacheName);
        }
    }
}
